import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:toast/toast.dart';
import 'package:peach/config/_.dart';
import 'package:peach/entity/_.dart';
import 'package:peach/service/_.dart';
import 'package:peach/utils/_.dart';
import 'package:peach/widget/_.dart';
import 'package:share_extend/share_extend.dart';

class DetailsIndex extends StatefulWidget {
  final String id;
  DetailsIndex({Key key, this.id }): super(key: key);

  @override
  State<StatefulWidget> createState() => _DetailsIndex();
}

class _DetailsIndex extends State<DetailsIndex> {

  List<String> imagePaths = [];
  AgentInfo Res;
  FreeUseEntity freeUseStatus;
  String title = "";
  bool LikeStatus = false;

  @override
  void initState() {
    super.initState();
    checkIdStatus();
    Core.freeUse(context, () {
      GetInfoData();
    });
  }

  Future<AgentInfo> GetInfoData() async {
    Res = await HomeService.GetInfoData(params: { 'id': widget.id });
    setState(() {
      imagePaths = Res.imgs;
      title = Res.title;
    });
  }


  /// 检查写真是否被收藏
  Future<bool> checkIdStatus () async {
    var status = await LikeService.find(int.parse(widget.id));
    setState(() {
      LikeStatus = status;
    });
  }

  /// 检查是否被收藏，爱心的改变样式
  Widget LikeStatusWidget () {
    return
      LikeStatus
          ? IconButton(icon: Icon(Icons.favorite, color: ColorConfig.WhiteBackColor,),iconSize: 24,)
          : IconButton(
        iconSize: 24,
        icon: LikeStatus ? Icon(Icons.favorite_border) : Icon(Icons.favorite_border),
        onPressed: () async {
          if (imagePaths.isNotEmpty) {
            if (Core.isVip(context)) {
              var User = LikeEntity(
                  id: int.parse(widget.id),
                  preview: imagePaths[0],
                  source: Res.jigoulist[0].name,
                  title: Res.title,
                  totals: Res.shuliang,
                  user: Res.renwulist[0].name
              );

              int result = await LikeService.addLike(User);
              if (result > 0) {
                Toast.show("写真收藏成功！", context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
                setState(() => LikeStatus = true);
              } else {
                Toast.show("写真收藏失败: ${result}", context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
              }
            } else {
              Toast.show("您还未开通VIP，无法使用【收藏图片】【收藏写真】【保存到相册】【成人视频】等功能", context, duration: Toast.LENGTH_LONG, gravity: Toast.CENTER);
            }
          } else {
            Toast.show("请稍后收藏，数据正在加载中...", context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
          }
        },
      );
  }

  /// 长按的弹出框
  actionDiaLog (String url) async {
    if (Core.isVip(context)) {
      await showDialog(
          context: context,
          builder: (context) {
            return SimpleDialog(
              titlePadding: EdgeInsets.all(15),
              contentPadding: EdgeInsets.all(15),
              title: Container(
                alignment: Alignment.centerLeft,
                child: Row(
                  children: [
                    Icon(Icons.touch_app,size: 30,color: ColorConfig.ThemeColor,),
                    SizedBox(width: 5,),
                    Text("请选择操作",style: TextStyle(fontSize: 17),)
                  ],
                ),
              ),
              children: <Widget>[
                FlatButton(
                    child: Text("保存到相册"),
                    onPressed: () {
                      Navigator.of(context).pop();
                      saveGallery(url);
                    }
                ),
                FlatButton(
                    child: Text("收藏此图片"),
                    onPressed: () async {
                      Navigator.of(context).pop();
                      singleLike(url);
                    }
                ),
              ],
            );
          }
      );
    } else {
      Toast.show("您还未开通VIP，无法使用【收藏图片】【收藏写真】【保存到相册】【成人视频】等功能", context, duration: Toast.LENGTH_LONG, gravity: Toast.CENTER);
    }
  }

  /// 保存图片到相册
  saveGallery(String url) async {
    // var path = await ImagePickers.saveImageToGallery(url);
    // path.length != 0
    //     ? Toast.show("图片存储在 ${path}", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM)
    //     : Toast.show("保存失败", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);

    var response = await DownloadService.downImage(url: url);
    String fileName = Tool.randomBit();
    final result = await ImageGallerySaver.saveImage(
        Uint8List.fromList(response),
        quality: 100,
        name: fileName
    );
    result['isSuccess']
        ? Toast.show("图片存储在 ${result['filePath']}", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM)
        : Toast.show("保存失败", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
  }

  /// 分享给好友
  shareImg() async {
    ShareExtend.share(
      "[有人@你]\n高清模特写真你要不要？？\n\n写真集名称：${Res.title}\n\n写真访问地址：${Config.h5IpUrl}info.html?id=${Res.id}\n\n浏览更多高清模特写真请下载应用：【屁桃儿】",
      "text",
      sharePanelTitle: "111",
    );
  }

  /// 单张图的收藏功能
  singleLike(String url) async {
    // false 可以收藏，true 收藏过了
    bool status = await LikeService.checkIsLike(url);
    print("status statusstatusstatusstatus : ${status}");
    if (status) {
      Toast.show("此图片已经收藏过啦！！", context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
    } else {
      var add = SingleGraphEntity(
        id: int.parse(widget.id) + int.parse(Tool.randomBit()),
        src: url
      );
      int result = await LikeService.addImg(add);
      if (result > 0) {
        Toast.show("图片收藏成功！", context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
      } else {
        Toast.show("图片收藏失败！", context, duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        backgroundColor: ColorConfig.ThemeColor,
        elevation: 0,
        actions: [
          LikeStatusWidget(),
          IconButton(
            icon: Icon(Icons.share_outlined,color: ColorConfig.WhiteBackColor,),iconSize: 24,
            onPressed: () {
              shareImg();
            },
          )
        ],
      ),
      body: imagePaths.isEmpty
          ? SpinKitWave(color: ColorConfig.ThemeColor, itemCount: 3, size: 40)
          : ListView.builder(
              itemCount: imagePaths.length,
              cacheExtent: double.maxFinite,
              itemBuilder: (BuildContext context, int index) {
                return InkWell(
                  onLongPress: () => actionDiaLog(imagePaths[index]),
                  onTap: () async {
                    ImagePickers.previewImages(imagePaths,index);
                    // Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                    //   return PhotoViewGalleryScreen(
                    //     images: imagePaths,
                    //     index: index,
                    //     title: Res.title,
                    //     time: Res.shijian,
                    //     heroTag: index.toString(),
                    //   );
                    // }));
                  },
                  child: CachedNetworkImg(imagePaths[index]),
                );
              },
            )
    );
  }

}